package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.BeanCopyUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.*;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.service.ProductAttrValueService;
import com.atguigu.gulimall.product.vo.AttrReqVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Autowired
    ProductAttrValueDao productAttrValueDao;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存属性,并保存关联的属性分组
     *
     * @param attrReqVo 封装的属性vo
     */
    @Transactional
    @Override
    public void saveAttr(AttrReqVo attrReqVo) {
        // 保存基本数据
        AttrEntity entity = BeanCopyUtils.copy(attrReqVo, AttrEntity.class);
        baseMapper.insert(entity);

        if (attrReqVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode()
                && attrReqVo.getAttrGroupId() != null) {
            // 保存关联的属性分组
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrReqVo.getAttrGroupId());
            relationEntity.setAttrId(entity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }

    }

    /**
     * 获取分类规格参数
     *
     * @param params    分页参数
     * @param type      属性类型{base, sale}
     * @param catelogId 分类id
     * @return 分类规格参数的分页数据
     */
    @Override
    public PageUtils queryBasePage(Map<String, Object> params, String type, Long catelogId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();

        // 查询属性类型
        if (StringUtils.equals("base", type)) {
            wrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        } else {
            wrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        }

        // 查询分类id
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        // 查询关键字
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(queryWrapper -> queryWrapper.eq("attr_name", key).or().like("attr_id", key));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        // 封装组名和分类名
        PageUtils pageUtils = new PageUtils(page);
        List<AttrRespVo> collect = page.getRecords().stream().map(attrEntity -> {
            AttrRespVo attrRespVo = BeanCopyUtils.copy(attrEntity, AttrRespVo.class);

            // 封装组名，基本属性才有分组
            if (StringUtils.equals("base", type)) {
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            // 封装分类名
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(collect);

        return pageUtils;
    }

    /**
     * 查询属性详情
     *
     * @param attrId 属性id
     * @return 属性详情
     */
    @Cacheable(value = "attr", key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = BeanCopyUtils.copy(attrEntity, AttrRespVo.class);

        // 封装分组id
        if (attrEntity.getValueType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrId));
            if (relationEntity != null) {
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 封装分类完整路径
        Long[] categoryPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(categoryPath);
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        return attrRespVo;
    }

    /**
     * 修改属性
     *
     * @param attrReqVo 商品属性的请求vo
     */
    @Transactional
    @Override
    public void updateAttr(AttrReqVo attrReqVo) {
        // 修改商品属性基本信息
        AttrEntity attrEntity = BeanCopyUtils.copy(attrReqVo, AttrEntity.class);
        this.updateById(attrEntity);

        if (attrEntity.getValueType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 修改商品属性与分组关联信息
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrReqVo.getAttrGroupId());
            // 如果存在，更新；否则，新增
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId()));
            if (count > 0) {
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrEntity.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }

    }

    /**
     * 获取spu规格
     *
     * @param spuId 商品id
     * @return spu规格属性值
     */
    @Override
    public List<ProductAttrValueEntity> queryBaseListForSpu(Long spuId) {
        List<ProductAttrValueEntity> valueEntityList = productAttrValueDao.selectList(
                new QueryWrapper<ProductAttrValueEntity>()
                        .eq("spu_id", spuId));
        return valueEntityList;
    }

    /**
     * 修改商品规格
     *
     * @param spuId                      商品id
     * @param productAttrValueEntityList spu属性值
     */
    @Transactional
    @Override
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> productAttrValueEntityList) {
        // 删除spuId对应的所有属性
        productAttrValueDao.delete(new QueryWrapper<ProductAttrValueEntity>()
                .eq("spu_id", spuId));

        // 新增spuId对应的所有属性
        List<ProductAttrValueEntity> collect = productAttrValueEntityList.stream()
                .peek(entity -> entity.setSpuId(spuId))
                .collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);

    }

    /**
     * 查询spu的所有可被检索的规格属性
     *
     * @param spuId 商品id
     * @return 可被检索的规格属性列表
     */
    @Override
    public List<Long> querySearchAttrsBySpuId(Long spuId) {
        List<ProductAttrValueEntity> valueEntityList = productAttrValueService.queryBySpuId(spuId);
        List<Long> attrIdList = valueEntityList.stream()
                .map(ProductAttrValueEntity::getAttrId)
                .collect(Collectors.toList());
        List<AttrEntity> attrEntityList = baseMapper.selectBatchIds(attrIdList);
        return attrEntityList.stream()
                .filter(item -> item.getSearchType() == 1)
                .map(AttrEntity::getAttrId)
                .collect(Collectors.toList());
    }

}